package lookas.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import lookas.model.Customer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//@Transactional
// @Repository("customerRepository")
public class CustomerRepositoryImpl implements CustomerRepository {

    private static Log    log = LogFactory.getLog(CustomerRepositoryImpl.class);

    @PersistenceContext
    private EntityManager em;

    public Customer findCustomerByPesel(String pesel) {
        long pre = System.currentTimeMillis();
        Customer customer = em.find(Customer.class, pesel);
        if (log.isDebugEnabled()) {
            long post = System.currentTimeMillis();
            long time = post - pre;
            log.debug(time + " millis");
        }
        return customer;
    }

    @SuppressWarnings("unchecked")
    public List<Customer> findAllCustomers() {
        Query query = em.createNamedQuery("Customer.findAll");
        query.setMaxResults(100);
        long pre = System.currentTimeMillis();
        List list = query.getResultList();
        if (log.isDebugEnabled()) {
            long post = System.currentTimeMillis();
            long time = post - pre;
            log.debug(time + " milis");
        }
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Customer> findLimitedCustomers(int offset, int limit) {
        Query query = em.createNamedQuery("Customer.findAll");
        limit = limit > 0 ? limit : 0;
        offset = offset > 0 ? offset : 0;
        query.setMaxResults(limit).setFirstResult(offset);
        long pre = System.currentTimeMillis();
        List list = query.getResultList();
        if (log.isDebugEnabled()) {
            long post = System.currentTimeMillis();
            long time = post - pre;
            log.debug(time + " milis");
        }
        return list;
    }

    public void save(Customer c) {
        em.merge(c);
    }

    public long size() {
        long pre = System.currentTimeMillis();
        Query query = em.createNamedQuery("Customer.size");
        if (log.isDebugEnabled()) {
            long post = System.currentTimeMillis();
            long time = post - pre;
            log.debug(time + " milis");
        }
        return (Long) query.getSingleResult();
    }

    @Override
    public void delete(Customer c) {
        // TODO Auto-generated method stub
    }
}
